<template>
  <div>
    <el-row>
      <el-col :span="8"></el-col>
      <el-col :span="8">
        <el-row class="margin-top-30vh">
          <el-form :model="loginForm" label-width="auto">
            <el-form-item label="用户">
              <el-input v-model="loginForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="loginForm.password" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitLogin">Login</el-button>
              <el-button type="default" @click="resetLogin">Reset</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </el-col>
      <el-col :span="8"></el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElNotification } from "element-plus";
import type Result from "@/types/common";
import useUserStore from "@/store/modules/user";

defineOptions({ name: "LoginView" });

const userStore = useUserStore();
const router = useRouter();
const loginForm = reactive({
  username: "",
  password: ""
});

const submitLogin = () => {
  if (loginForm.username.trim() == "" || loginForm.password.trim() == "") {
    ElNotification({
      message: "用户名或密码不能为空",
      type: "error"
    });
    return;
  }
  userStore.userLogin(loginForm).then((res: Result) => {
    if (res.code != "200") {
      ElNotification({
        message: res.message,
        type: "error"
      });
      return;
    }
    localStorage.setItem("token", res.data.token);
    localStorage.setItem("username", res.data.user.username);
    ElNotification({
      message: "欢迎回来",
      title: "Hi, " + localStorage.getItem("username"),
      type: "success"
    });

    // router 跳转到 home
    router.push("/home");
  });
};
const resetLogin = () => {
  loginForm.username = "";
  loginForm.password = "";
};

onMounted(() => {
  // 获取 token
  // const token = localStorage.getItem("token");
  // if (token) {
  //   router.push("/home");
  // }
});
</script>
